package com.whoyx.jiebing.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;

import javax.validation.constraints.NotBlank;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * @author stone
 */
public class OpenCodeUtils {

    private final static int ID_MIN_VALUE = 147292;
    private final static int ID_MAX_VALUE = 999999;

    private final static String[] CHARS = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    /**
     * 生成app_id
     * @return wh+(16位)
     */
    public static String generateAppId() {
        return "wh" + generateCode(16);
    }

    /**
     * 生成app_secret
     * @return 32位
     */
    public static String generateAppSecret(String appId) {
        try {
            String salt = RandomUtil.randomString(8);
            String str = appId + salt;
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            StringBuilder builder = new StringBuilder();
            String shaHex;
            for (byte b : digest) {
                shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    builder.append(0);
                }
                builder.append(shaHex);
            }
            return builder.toString();
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 生成用户code（只能用一次且5分钟内有效）
     * @return 64位code
     */
    public static String generateUserCode() {
        return generateCode(64);
    }

    /**
     * 生成用户账号id
     * @return uid+16位code
     */
    public static String generateUserId(int role) {
        String pre = "";
        if (role == 1) {
            pre = "dr_";
        } else if (role == 2) {
            pre = "pat_";
        }
        return pre + generateCode(16);
    }

    /**
     * 生成报告单号 28位
     * @param id 6位id
     * @return 40 + 年 + 时间戳 + 6位id + 6位随机数
     */
    public static String generateEvaReportCode(int id) {
        return generateReportCode("40", id);
    }

    /**
     * 生成报告单号 28位
     * @param id 6位id
     * @return 42 + 年 + 时间戳 + 6位id + 6位随机数
     */
    public static String generateDataReportCode(int id) {
        return generateReportCode("42", id);
    }

    /**
     * 生成报告单号 28位
     * @param prefix 标志位，建议长度为2
     * @param id 6位id
     * @return 42 + 年 + 时间戳 + 6位id + 6位随机数
     */
    public static String generateReportCode(@NotBlank String prefix, int id) {
        id = id + ID_MIN_VALUE;
        if (id > ID_MAX_VALUE) {
            id = id % ID_MAX_VALUE;
            id = id + ID_MIN_VALUE;
        }
        int year = LocalDateTimeUtil.now().getYear();
        long time = System.currentTimeMillis() / 1000;
        String randomNum = RandomUtil.randomNumbers(6);
        return prefix + year + time + id + randomNum;
    }


    /**
     * 生成code
     * @param length 长度
     * @return code
     */
    public static String generateCode(int length) {
        int count = length / 8;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i <= count; i++) {
            builder.append(generateCode());
        }
        return builder.substring(0, length).toLowerCase();
    }

    /**
     * 生成8位code
     * @return 8位code
     */
    public static String generateCode() {
        int length = 8;
        StringBuilder builder = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < length; i++) {
            String s = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(s, 16);
            builder.append(CHARS[x % 0x24]);
        }
        return builder.toString().toLowerCase();
    }

    public static void main(String[] args) {

        String appId = generateAppId();
        String appSecret = generateAppSecret(appId);
        System.out.println("appId: " + appId);
        System.out.println("appSecret: " + appSecret);

//        LocalDateTime startTime = LocalDateTimeUtil.parse("2022-03-16 22:10:22", DatePattern.NORM_DATETIME_PATTERN);
//        LocalDateTime endTime = LocalDateTimeUtil.parse("2022-03-16 20:11:22", DatePattern.NORM_DATETIME_PATTERN);
//        LocalDateTime endTime1 = LocalDateTimeUtil.parse("2022-03-17 01:10:22", DatePattern.NORM_DATETIME_PATTERN);
//        int a = Math.toIntExact(LocalDateTimeUtil.between(LocalDateTimeUtil.beginOfDay(startTime), endTime, ChronoUnit.SECONDS));
//        int a1 = Math.toIntExact(LocalDateTimeUtil.between(LocalDateTimeUtil.beginOfDay(startTime), endTime1, ChronoUnit.SECONDS));
//        System.out.println(a);
//        System.out.println(a1);
//        System.out.println(LocalDateTimeUtil.beginOfDay(startTime).plusSeconds((a + a1)/2));

//        String uid = generateUserId();
//        String salt = generateCode(6);
//        String password = SaSecureUtil.md5BySalt("123456", salt);
//        System.out.println(uid);
//        System.out.println(salt);
//        System.out.println(password);

//        List<QuestionTimePicker> pickers = new ArrayList<>();
//        for (int i = 0; i < 3; i++) {
//            if (i == 0) {
//                List<String> values = new ArrayList<>();
//                for (int j = 0; j < 24; j++) {
//                    values.add(String.valueOf(j + 1));
//                }
//                QuestionTimePicker picker = QuestionTimePicker.builder().name("小时").unit("h").values(values).build();
//                pickers.add(picker);
//            }else if (i == 1) {
//                List<String> values = new ArrayList<>();
//                for (int j = 0; j < 30; j++) {
//                    values.add(String.valueOf(j + 1));
//                }
//                QuestionTimePicker picker = QuestionTimePicker.builder().name("天").unit("d").values(values).build();
//                pickers.add(picker);
//            }else {
//                List<String> values = new ArrayList<>();
//                for (int j = 0; j < 24; j++) {
//                    values.add(String.valueOf(j + 1));
//                }
//                QuestionTimePicker picker = QuestionTimePicker.builder().name("个月").unit("m").values(values).build();
//                pickers.add(picker);
//            }
//        }
//        String s = JSONUtil.toJsonStr(pickers);
//        System.out.println(s);




    }


}
